package com.sunxiansheng.redis.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Description: Spring上下文工具类
 * @Author sun
 * @Create 2024/7/19 12:40
 * @Version 1.0
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 这个方法，可以从容器中获取Spring上下文，但是必须要注入容器才可以被调用
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 从Spring容器中根据Class类型获取bean对象
     *
     * @param clazz
     * @return
     */
    public static Object getBean(Class<?> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 获取Spring的上下文
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

}